package com.cly.authCode.service.impl;

import com.cly.authCode.service.AuthCodeService;
import com.cly.common.content.AuthCodeContent;
import com.cly.common.exception.AuthCodeException;
import com.cly.common.util.AuthCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 发送登入验证码
     * @param phoneNumber
     */
    @Override
    public void sendLoginAuthCode(String phoneNumber) {
        // 生成6为随机的字符串验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        // 调用工具类发送短信
        try {
            AuthCodeUtil.sendCode(phoneNumber, code);
            stringRedisTemplate.opsForValue()
                    .set(AuthCodeContent.AUTH_CODE_LOGIN_REDIS_KEY + phoneNumber, code,
                            AuthCodeContent.AUTH_CODE_TIME, TimeUnit.MINUTES);
            log.info("发送登入验证码成功，验证码为：{}", code);
        } catch (Exception e) {
            throw new AuthCodeException(AuthCodeContent.AUTH_CODE_SEND_ERROR);
        }
    }

    /**
     * 发送注册验证码
     * @param phoneNumber
     */
    @Override
    public void sendRegisterAuthCode(String phoneNumber) {
        // 生成6为随机的字符串验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        // 调用工具类发送短信
        try {
            AuthCodeUtil.sendCode(phoneNumber, code);
            stringRedisTemplate.opsForValue()
                    .set(AuthCodeContent.AUTH_CODE_REGISTER_REDIS_KEY + phoneNumber, code,
                            AuthCodeContent.AUTH_CODE_TIME, TimeUnit.MINUTES);
            log.info("发送注册验证码成功，验证码为：{}", code);
        } catch (Exception e) {
            throw new AuthCodeException(AuthCodeContent.AUTH_CODE_SEND_ERROR);
        }
    }
}
